from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
# 导入对应产品模块的client models。
from tencentcloud.sms.v20210111 import sms_client, models

# 导入可选配置类
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile

# 导入随机模块 产生验证码
import random

# 导入配置文件
from .settings import tx_sms_settings
from utils.loggers import logger

# 将发送短信设置为celery任务
from celery1 import app


def get_code(num=4):
    code = ''
    for i in range(num):
        tem = random.randint(0, 9)
        code += str(tem)
    return code


@app.task
def send_sms(mobile, code):
    try:
        cred = credential.Credential(tx_sms_settings.SECRET_ID, tx_sms_settings.SECRET_KEY)
        # 实例化一个http选项，可选的，没有特殊需求可以跳过。
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 30  # 请求超时时间，单位为秒(默认60秒)
        httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

        # 实例化一个客户端配置对象，可以指定超时时间等配置
        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
        clientProfile.language = "en-US"
        clientProfile.httpProfile = httpProfile

        client = sms_client.SmsClient(cred, "ap-nanjing", clientProfile)
        req = models.SendSmsRequest()
        req.SmsSdkAppId = tx_sms_settings.SMS_SDK_APPID
        # 短信签名内容: 使用 UTF-8 编码，必须填写已审核通过的签名
        req.SignName = tx_sms_settings.SIGN_NAME
        # 模板 ID: 必须填写已审核通过的模板 ID
        req.TemplateId = tx_sms_settings.TEMPLATE_ID
        # 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致，，若无模板参数，则设置为空
        req.TemplateParamSet = [code]
        # 发送对象
        req.PhoneNumberSet = [f"+86{mobile}"]
        req.SessionContext = ""
        req.ExtendCode = ""
        req.SenderId = ""

        resp = client.SendSms(req)

        # 根据返回结果进行判断返回结果
        sms_status = resp.SendStatusSet[0].Code
        sms_message = resp.SendStatusSet[0].Message
        if sms_status != 'Ok':
            logger.error(f'短信发送失败|对方{mobile}|{sms_status}|{sms_message}')
            return False
        else:
            return True
    except TencentCloudSDKException as err:
        logger.error(f'短信发送失败|{err}')
        return False
